from uuid import uuid4
import hashlib
import time
import os
from rest_framework.response import Response
from jwt import JWT, jwk_from_dict, jwk_from_pem
from datetime import datetime, timedelta, timezone
from jwt.utils import get_int_from_datetime

#pub_key、pri_key使用下面这个网址生成，然后直接粘贴进来就ok了
#https://mkjwk.org/?spm=a2c4g.11186623.2.20.2aed167chumlVx

# 根据用户传递的值用私钥加密，签名，公钥解密、解签
class JwtToken:
    pub_key = {  "p": "2seX1CX5mDHneQMwzqAjCuzX87txUrTUbYIiSXUmxpsgf2F2ioBmRsV0tbMYAO1XXqXTGGYIQiasr_WRGM0TZoVNWZz2ZBvViERcq7guszon1eU1-ulC5dAVRlgMWiId4Xppl17MYQbKSeTbqgGVc9o_jnLfyyN7ekJvWCfjD28",
    "kty": "RSA",
    "q": "vY4hBn_ZFxb1sbCE-4kRTA2OHTl8dGgYsOsQq7MLpl9fvSn5KaBPR9rpUBrRuDxAGzVnJhrFmJa5Ou0f0epMVqI0ItkYY0ataZmplk8CoonwMH8oq2DYREpo8BiROykQxHAxUrewq1YyRxwyMMMk76gbP0SybLftGX2JcJw8oyk",
    "d": "DwTM_BQkr5v110dL878q8xvUwwLqHGlGwpSZWqNDk1sl-OHVB2Xp3YfqnPk0P1GcJQJRNSWkihgXZXalV6ko6MF153MgiDaD1CAZVvxIQ3ARGl0-Ica-J5rgpp3qqkenjY5qL2M1_v9IN0zPq2MZPrefyCMVgMbFIUejuBT23FnMuhiCTA7ppi0u4mn1Xv3XTaKD8XnKDkDKma1FbBUfV_Gbu0wmejNd1699wiaoATXNwgqQsgz_ahZRDL-utbSzODEdhWC8rbhJqG4RfLqdb5LEzUZGLDBlZuXyCIq5XaFhJP6oiIhlL1CKIz0pLwKg1VgU3_mMC_iwcUrCRdjnQQ",
    "e": "AQAB",
    "qi": "qIyG0uWBuwhWOT0lIM4LUzeSwDt6WWLf7Q9cTiVRviFmGpGoeLWfNvqt7dM9MykJrSaWlqJ17645B53VNdOsqIMh-gvmVIPjUISa8JLp5_7YXoMlsXe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AJ6SGfW9Xt6OVgkNOD965rGJ6xgY3Kf3uXmATdxsH8Vd23Er1718GjQ4xJCfp8PnR1zHZwWUp4FC7_bwn9Sagn8R9LJ9Ok0Dc-fWTEicBUqAsl_tboVD1-PWvawszVJVnEbo6toTfbeisHae8tMsMVkwcvQwFXfpKMEjdo4EWZjAmfrcuzWzwpoAVw4veWCf3dsco1GsLim1hcADV_S8Vf-wrj3OcVDmAQkiMrQWogA5mWCS-H8tBw0BLE6nhgJTNSzODUlxw"}

    def encode_token(self, data, set_time=24000):
        # with open("./pri.pem", 'rb') as f:
        #     jwk_from_pem(f.read())
        signing_key = jwk_from_dict(self.pri_key)
        instance = JWT()
        # print(signing_key.to_dict())
        data['iat'] = get_int_from_datetime(datetime.now(timezone.utc))
        data['exp'] = get_int_from_datetime(datetime.now(timezone.utc) + timedelta(hours=set_time))
        # print(data)
        return instance.encode(payload=data, key=signing_key, alg='RS256')

    def decode_token(self, data):
        verifying_key = jwk_from_dict(self.pub_key)
        instance = JWT()
        return instance.decode(data, verifying_key, do_time_check=True)

# 哈希密码
def pwd_hash(val):
    slat = 'zheshiyan'
    md5 = hashlib.md5()

    # print(val, slat)
    md5.update((val+slat).encode('utf-8'))
    return md5.hexdigest()

#重写返回值格式
def info(data='', status=1, message='', headers=None):
    res = Response()
    res.data = {
        'status': status,
        'message': message,
        'data': data
    }
    if headers:
        for k, v in headers.items():
            res[k] = v
    return res
# if __name__ == '__main__':
#     J = JwtToken()
#     print(J.encode_token({'uuid': 123165165165}))
#     print(J.decode_token(J.encode_token({'uuid': 123165165165})))
#     print(J.encode_token({'uuid': 123165165165}))
#     print(J.decode_token(J.encode_token({'uuid': 123165165165})))
#